import React, { Component } from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Button, Card, Form, message, Modal, Table } from 'antd';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import moment from 'moment';
import GroupModal from './groupModal';
import AddFieldModal from './addFieldModal';
import Ellipsis from '../../../components/Ellipsis';
import { filterAuth } from '@/support/common';

const FieldTypes = {
  1: '文本',
  2: '下拉列表',
  3: '数字',
  4: '日期',
  5: '时间',
  6: '日期时间',
  7: 'URL链接',
};

const FieldStatus = {
  0: '未生效',
  1: '生效中',
  2: '已停用',
};

class FieldSetting extends Component {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  state = {
    formValues: {},
    groupModalVisible: false,
    addModalVisible: false,
    fieldDetailData: {},
  };

  componentDidMount() {
    this.refreshPage();
  }

  refreshPage() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'fieldSetting/settingCount',
      payload: {
        url: '/mscreditbusiness/credit/field/setting/count',
      },
    });
    dispatch({
      type: 'fieldSetting/groupList',
      payload: {
        url: '/mscreditbusiness/credit/field/group/list',
      },
    });
    dispatch({
      type: 'fieldSetting/fieldSettingList',
      payload: {
        url: '/mscreditbusiness/credit/field/setting/list',
        ...formValues,
      },
    });
  }
  handleStatus = (uuid, status) => {
    //  status: 字段状态
    //  1 – 启用
    //  2 – 停用
    const { dispatch } = this.props;
    dispatch({
      type: 'fieldSetting/fieldSettingStatus',
      payload: {
        url: '/mscreditbusiness/credit/field/setting/status',
        uuid,
        status,
      },
      callback: (res) => {
        if (res.statusCode == '0') {
          message.success('操作成功');
          this.refreshPage();
        } else {
          message.error(res.statusMessage);
        }
      },
    });
  };
  handleEdit = (uuid) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fieldSetting/fieldSettingDetail',
      payload: {
        url: '/mscreditbusiness/credit/field/setting/detail',
        uuid,
      },
      callback: (res) => {
        if (res.statusCode == '0') {
          this.setState(
            {
              fieldDetailData: res.data,
            },
            () => {
              this.setState({ addModalVisible: true });
            },
          );
        } else {
          this.setState(
            {
              fieldDetailData: {},
            },
            () => {
              this.setState({ addModalVisible: true });
            },
          );
          message.error(res.statusMessage);
        }
      },
    });
  };
  handleDelete = (uuid) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fieldSetting/fieldSettingDel',
      payload: {
        url: '/mscreditbusiness/credit/field/setting/delete',
        uuid,
      },
      callback: (res) => {
        if (res.statusCode == '0') {
          message.success('删除成功');
          this.refreshPage();
        } else {
          message.error(res.statusMessage);
        }
      },
    });
  };

  render() {
    const {
      fieldSetting: { loading: fieldsLoading, fieldSettingList, groupList, groupCount, fieldCount },
      dispatch,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const { groupModalVisible, addModalVisible, fieldDetailData } = this.state;
    const startBtnAuth = filterAuth('fieldSetting-start', permissions, pathname);
    const stopBtnAuth = filterAuth('fieldSetting-stop', permissions, pathname);
    const editBtnAuth = filterAuth('fieldSetting-edit', permissions, pathname);
    const delBtnAuth = filterAuth('fieldSetting-delete', permissions, pathname);
    const groupAuth = filterAuth('fieldSetting-group', permissions, pathname);
    const addAuth = filterAuth('fieldSetting-add', permissions, pathname);
    const groupOptions = groupList.map((item) => {
      return {
        value: item.uuid,
        label: item.name,
      };
    });
    const searchItems = [
      {
        type: 'input',
        title: '字段名称',
        key: 'name',
      },
      {
        type: 'select',
        title: '字段分组',
        key: 'groupId',
        selectOptions: groupOptions,
      },
    ];
    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        render: (text, record, index) => {
          return index + 1;
        },
      },
      {
        title: '字段名称',
        dataIndex: 'name',
      },
      {
        title: '所属分组',
        dataIndex: 'groupName',
      },
      {
        title: '字段类型',
        dataIndex: 'type',
        render: (text, record) => {
          return record.name === '预警信息列表' || record.name === '风控操作记录列表'
            ? '列表'
            : FieldTypes[text];
        },
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render: (text) => {
          return text === 'sys' ? '系统' : text;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text, row) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '字段状态',
        dataIndex: 'status',
        render: (text) => FieldStatus[text],
      },
      {
        title: '字段应用商户',
        dataIndex: 'merchant',
        render: (val) => (
          <Ellipsis length={16} tooltip>
            {val}
          </Ellipsis>
        ),
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 160,
        fixed: 'right',
        align: 'center',
        render: (text, record) => {
          const btns = [];
          const startBtn = {
            title: '启用',
            key: 'start',
            auth: 'fieldSetting-start',
            Popconfirm: true,
            message: '确认要启用吗？',
            onConfirm: () => this.handleStatus(record?.uuid, 1),
          };
          const stopBtn = {
            title: '停用',
            key: 'stop',
            auth: 'fieldSetting-stop',
            Popconfirm: true,
            message: '确认要停用吗？',
            onConfirm: () => this.handleStatus(record?.uuid, 2),
          };
          const delBtn = {
            title: '删除',
            key: 'delete',
            auth: 'fieldSetting-delete',
            Popconfirm: true,
            message: '确认要删除吗？',
            onConfirm: () => this.handleDelete(record?.uuid),
          };
          const editBtn = {
            title: '修改',
            key: 'edit',
            auth: 'fieldSetting-edit',
            onConfirm: () => this.handleEdit(record?.uuid),
          };
          if (record?.defaultType == 1) {
            // 不为 系统预设字段 才有操作按钮
            if (record?.status == 1) {
              //  字段状态-已生效:停用
              //  字段被商户使用则无停用按钮
              !record?.merchant && btns.push(stopBtn);
            } else if (record?.status == 2) {
              //  字段状态-已停用:启用 删除
              btns.push(startBtn);
              btns.push(delBtn);
              // } if (record?.status == 0) {
            } else {
              //  字段状态-未生效:删除、修改、启用
              btns.push(startBtn);
              btns.push(editBtn);
              btns.push(delBtn);
            }
          }
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{
              type: 'fieldSetting/fieldSettingList',
              url: '/mscreditbusiness/credit/field/setting/list',
            }}
            dispatch={dispatch}
            saveFormValues={(val) =>
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {groupAuth && (
              <Button
                size="small"
                type="primary"
                onClick={() => this.setState({ groupModalVisible: true })}
              >
                {`字段分组（${groupCount}/10）`}
              </Button>
            )}
            {addAuth && (
              <Button
                size="small"
                type="primary"
                style={{ marginLeft: '12px' }}
                onClick={() => {
                  this.setState(
                    {
                      fieldDetailData: {},
                    },
                    () => {
                      this.setState({ addModalVisible: true });
                    },
                  );
                }}
              >
                {`新增字段（${fieldCount}/100）`}
              </Button>
            )}
          </div>

          <Table
            // loading={fieldsLoading}
            rowKey={(record) => record.uuid}
            dataSource={fieldSettingList}
            columns={columns}
            pagination={false}
            size="middle"
          />

          {groupModalVisible && (
            <GroupModal
              visible={groupModalVisible}
              changeVisible={() => {
                this.setState({ groupModalVisible: false });
                this.refreshPage();
              }}
            />
          )}
          {addModalVisible && (
            <AddFieldModal
              visible={addModalVisible}
              formData={fieldDetailData}
              changeVisible={() => {
                this.setState({ addModalVisible: false });
                this.refreshPage();
              }}
            />
          )}
        </Card>
      </div>
    );
  }
}
export default connect((state) => {
  return {
    common: state.common,
    loading: state.loading.effects['common/pageGet'],
    permissions: state?.menu?.permissions,
    fieldSetting: state.fieldSetting,
  };
})(FieldSetting);
